package com.utf999.qiangmanger.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.utf999.qiangmanger.controller.permission.AuthorityAnnotation;
import com.utf999.qiangmanger.controller.permission.AuthorityScope;
import com.utf999.qiangmanger.controller.permission.PromptModeType;

import com.utf999.qiangmanger.exception.AuthenticationException;

import com.utf999.qiangmanger.service.iface.IAdminUserService;

/**
 * 用户鉴权相关的页面处理器
 * @author yinwenjie
 */
@Controller
public class AdminUserSecurityController extends BaseController {
	
	@Autowired
	private IAdminUserService adminUserService;
	
	@RequestMapping(value={"/loginform"})
	public ModelAndView loginform(HttpServletRequest request , HttpServletResponse response) {
		//到一个jsp页面
		ModelAndView mv = new ModelAndView("logninform");
		return mv;
	}
	
	/**
	 * 登录后到首页
	 * @param request
	 * @return 
	 * @throws AuthenticationException
	 */
	@RequestMapping(value={"/index"})
	@AuthorityAnnotation(scope={AuthorityScope.SuperAdmin,AuthorityScope.CompanyAdmin,AuthorityScope.StoreAdmin,AuthorityScope.Cashier} , promptMode=PromptModeType.REDIRECT)
	public ModelAndView index(HttpServletRequest request) throws AuthenticationException {
		//这里，我们摸出cookie，然后查询这个管理员的基本信息
		ModelAndView mv = new ModelAndView("index");
		return mv;
	}
	
	/**
	 * 控制台用户登录的操作。<br>
	 * 所谓控制台用户就是存储在AdminUser数据表中的，可以操作后台的用户。超级管理员、店面管理员、收银员
	 * @param request 
	 * @param response 
	 * @param username 登录时使用的用户民
	 * @param password 登录的密码（未加密）
	 * @return 
	 * @throws AuthenticationException 如果登录错误，会抛出这个异常，然后再web.xml中跳转到登录表单界面
	 */
	@RequestMapping(value={"/consoleUserLogon"} , method=RequestMethod.POST)
	public ModelAndView consoleUserLogon(HttpServletRequest request , HttpServletResponse response , String username , String password) throws AuthenticationException {
		String token = this.adminUserService.consoleUserLogon(username, password); 
		//写入到cookeis中
		this.writeToken(response, token);
		
		//注意滴跳转到index，不是直接返回到index。这是为了避免F5刷新
		ModelAndView mv = new ModelAndView("redirect:index");
		return mv;
	}
	
	/**
	 * 用户登出
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value={"/logout"} , method=RequestMethod.GET)
	public ModelAndView logout(HttpServletRequest request , HttpServletResponse response) {
		//注销cookeis信息
		this.unwriteToken(response);
		
		ModelAndView mv = new ModelAndView("redirect:loginform");
		return mv;
	}
}